<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Device extends Model
{
    //
    protected $fillable = ['code', 'kind_id', 'agency_id', 'get_time'];

    protected $dates = ['get_time'];

    public function kind()
    {
        return $this->belongsTo(Kind::class);
    }

    public function agency()
    {
        return $this->belongsTo(Agency::class);
    }

    public function historys()
    {
        return $this->hasMany(History::class);
    }

    public function currentChildren()
    {
        return $this->hasMany(CurrentChild::class, 'code', 'device_code');
    }

    public function deviceGrades(){
        return $this->hasMany(DeviceGrade::class);
    }
    public function grades(){
        return $this->belongsToMany(Grade::class,'device_grades');
    }
    public static function add($data)
    {
        $codesStr = str_replace('，', ',', $data['codes']);
        $codeArr = explode(',', $codesStr);
        if (empty($codeArr)) {
            return false;
        }
        $hasDevices = self::where('kind_id', $data['kind_id'])->whereIn('code', $codeArr)->get();

        if (count($hasDevices) > 0) {
            return false;
        }

        DB::beginTransaction();
        try {
            $kind = Kind::find($data['kind_id']);

            if (!$kind) {
                throw new \Exception('');
            }

            $codes = [];
            foreach ($codeArr as $code) {
                if (!empty($code)) {
                    $codes[] = [
                        'code' => $code,
                        'get_time' => $data['get_time'],
                        'agency_id' => $data['agency_id']
                    ];
                }
            }

            $kind->devices()->createMany($codes);

            DB::commit();
            return true;
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            DB::rollBack();
            return false;
        }
    }
    public static function selectQuery($data){
        return function ($query) use ($data) {
            if (isset($data['agency_id']) && $data['agency_id'] > 0) {
                $query->where('agency_id', $data['agency_id']);
            }
            if (isset($data['kind_id']) && $data['kind_id'] > 0) {
                $query->where('kind_id', $data['kind_id']);
            }
            if (isset($data['code']) && !empty($data['code'])) {
                $query->where('code', 'like', '%' . $data['code'] . '%');
            }
        };
    }
}
